#!/bin/bash

# 低代码AI平台部署脚本
# 支持开发环境、测试环境、生产环境部署

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    
    # 检查Docker服务状态
    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动，请先启动Docker服务"
        exit 1
    fi
    
    log_success "系统依赖检查完成"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    mkdir -p docker/mysql/data
    mkdir -p docker/mysql/conf
    mkdir -p docker/redis/data
    mkdir -p docker/redis/conf
    mkdir -p docker/milvus/data
    mkdir -p docker/milvus/configs
    mkdir -p docker/minio/data
    mkdir -p docker/nacos/logs
    mkdir -p docker/nacos/conf
    mkdir -p docker/prometheus/data
    mkdir -p docker/grafana/data
    mkdir -p docker/grafana/provisioning
    
    log_success "目录创建完成"
}

# 生成配置文件
generate_configs() {
    log_info "生成配置文件..."
    
    # Redis配置
    cat > docker/redis/conf/redis.conf << EOF
# Redis配置文件
bind 0.0.0.0
port 6379
timeout 0
tcp-keepalive 300
daemonize no
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile ""
databases 16
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./
maxmemory 256mb
maxmemory-policy allkeys-lru
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
EOF

    # Prometheus配置
    cat > docker/prometheus/prometheus.yml << EOF
global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'spring-boot'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['gateway:8080', 'auth-service:8081', 'user-service:8082', 'workflow-service:8083', 'rag-service:8084', 'plugin-service:8085']

  - job_name: 'milvus'
    static_configs:
      - targets: ['milvus:9091']
EOF

    log_success "配置文件生成完成"
}

# 启动基础设施
start_infrastructure() {
    log_info "启动基础设施服务..."
    
    docker-compose up -d mysql redis nacos milvus minio prometheus grafana
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 30
    
    # 检查服务状态
    check_service_health
    
    log_success "基础设施服务启动完成"
}

# 检查服务健康状态
check_service_health() {
    log_info "检查服务健康状态..."
    
    # 检查MySQL
    if ! docker-compose exec mysql mysqladmin ping -h localhost -u root -proot123456 --silent; then
        log_warning "MySQL服务可能未完全启动，请稍后重试"
    else
        log_success "MySQL服务正常"
    fi
    
    # 检查Redis
    if ! docker-compose exec redis redis-cli ping &> /dev/null; then
        log_warning "Redis服务可能未完全启动，请稍后重试"
    else
        log_success "Redis服务正常"
    fi
    
    # 检查Nacos
    if ! curl -s http://localhost:8848/nacos/v1/console/health/readiness &> /dev/null; then
        log_warning "Nacos服务可能未完全启动，请稍后重试"
    else
        log_success "Nacos服务正常"
    fi
}

# 构建后端服务
build_backend() {
    log_info "构建后端服务..."
    
    # 编译公共模块
    cd backend/lowcode-ai-common
    mvn clean install -DskipTests
    
    # 构建各个服务
    services=("lowcode-ai-gateway" "lowcode-ai-auth" "lowcode-ai-user" "lowcode-ai-workflow" "lowcode-ai-rag" "lowcode-ai-plugin")
    
    for service in "${services[@]}"; do
        log_info "构建服务: $service"
        cd ../$service
        mvn clean package -DskipTests
    done
    
    cd ../..
    log_success "后端服务构建完成"
}

# 构建前端服务
build_frontend() {
    log_info "构建前端服务..."
    
    # 构建管理后台
    cd frontend/lowcode-ai-admin
    npm install
    npm run build
    
    # 构建工作流设计器
    cd ../lowcode-ai-designer
    npm install
    npm run build
    
    cd ../..
    log_success "前端服务构建完成"
}

# 启动应用服务
start_application() {
    log_info "启动应用服务..."
    
    docker-compose up -d gateway auth-service user-service workflow-service rag-service plugin-service admin-frontend designer-frontend
    
    log_success "应用服务启动完成"
}

# 初始化数据
init_data() {
    log_info "初始化系统数据..."
    
    # 等待服务完全启动
    sleep 60
    
    # 这里可以添加数据初始化脚本
    # 例如：创建默认用户、配置默认模型等
    
    log_success "数据初始化完成"
}

# 显示部署信息
show_deployment_info() {
    log_success "部署完成！"
    echo ""
    echo "=== 服务访问地址 ==="
    echo "管理后台: http://localhost:3000"
    echo "工作流设计器: http://localhost:3001"
    echo "API网关: http://localhost:8080"
    echo "Nacos控制台: http://localhost:8848/nacos (admin/admin)"
    echo "MinIO控制台: http://localhost:9001 (minioadmin/minioadmin)"
    echo "Grafana监控: http://localhost:3002 (admin/admin123)"
    echo ""
    echo "=== 默认账号 ==="
    echo "管理后台: admin/admin123"
    echo ""
    echo "=== 常用命令 ==="
    echo "查看服务状态: docker-compose ps"
    echo "查看服务日志: docker-compose logs -f [service-name]"
    echo "停止所有服务: docker-compose down"
    echo "重启服务: docker-compose restart [service-name]"
    echo ""
}

# 开发环境部署
deploy_dev() {
    log_info "开始开发环境部署..."
    
    check_dependencies
    create_directories
    generate_configs
    start_infrastructure
    
    log_success "开发环境部署完成"
    show_deployment_info
}

# 测试环境部署
deploy_test() {
    log_info "开始测试环境部署..."
    
    check_dependencies
    create_directories
    generate_configs
    start_infrastructure
    build_backend
    build_frontend
    start_application
    init_data
    
    log_success "测试环境部署完成"
    show_deployment_info
}

# 生产环境部署
deploy_prod() {
    log_info "开始生产环境部署..."
    
    # 生产环境需要额外的安全检查
    log_warning "生产环境部署需要额外的安全配置"
    
    check_dependencies
    create_directories
    generate_configs
    start_infrastructure
    build_backend
    build_frontend
    start_application
    init_data
    
    log_success "生产环境部署完成"
    show_deployment_info
}

# 停止服务
stop_services() {
    log_info "停止所有服务..."
    docker-compose down
    log_success "服务已停止"
}

# 重启服务
restart_services() {
    log_info "重启所有服务..."
    docker-compose restart
    log_success "服务已重启"
}

# 查看服务状态
show_status() {
    log_info "查看服务状态..."
    docker-compose ps
}

# 查看服务日志
show_logs() {
    local service=$1
    if [ -z "$service" ]; then
        log_info "查看所有服务日志..."
        docker-compose logs -f
    else
        log_info "查看服务 $service 的日志..."
        docker-compose logs -f $service
    fi
}

# 清理环境
cleanup() {
    log_warning "清理环境将删除所有数据，请确认！"
    read -p "确认清理环境？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "开始清理环境..."
        docker-compose down -v
        docker system prune -f
        rm -rf docker/*/data
        log_success "环境清理完成"
    else
        log_info "取消清理操作"
    fi
}

# 显示帮助信息
show_help() {
    echo "低代码AI平台部署脚本"
    echo ""
    echo "用法: $0 [命令] [选项]"
    echo ""
    echo "命令:"
    echo "  dev         部署开发环境（仅基础设施）"
    echo "  test        部署测试环境（完整部署）"
    echo "  prod        部署生产环境（完整部署+安全检查）"
    echo "  stop        停止所有服务"
    echo "  restart     重启所有服务"
    echo "  status      查看服务状态"
    echo "  logs [服务] 查看服务日志"
    echo "  cleanup     清理环境（删除所有数据）"
    echo "  help        显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 dev                    # 部署开发环境"
    echo "  $0 test                   # 部署测试环境"
    echo "  $0 logs gateway           # 查看网关服务日志"
    echo "  $0 cleanup                # 清理环境"
}

# 主函数
main() {
    case "$1" in
        "dev")
            deploy_dev
            ;;
        "test")
            deploy_test
            ;;
        "prod")
            deploy_prod
            ;;
        "stop")
            stop_services
            ;;
        "restart")
            restart_services
            ;;
        "status")
            show_status
            ;;
        "logs")
            show_logs $2
            ;;
        "cleanup")
            cleanup
            ;;
        "help"|"-h"|"--help"|"")
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 